﻿// -------------------------------------------------------------------------
//    @FileName         :    NFWelfareMgr.cpp
//    @Author           :    gaoyi
//    @Date             :    2025-07-26
//    @Email			:    445267987@qq.com
//    @Module           :    NFWelfareMgr
//
// -------------------------------------------------------------------------

#include "NFWelfareMgr.h"

#include "NFServiceWelfare.h"
#include "proto_svr_common.nanopb.h"

#include "NFLogicCommon/NFWelfareConf.h"

NFWelfareMgr::NFWelfareMgr()
{
    if (EN_OBJ_MODE_INIT == NFShmMgr::Instance()->GetCreateMode())
    {
        CreateInit();
    }
    else
    {
        ResumeInit();
    }
}

NFWelfareMgr::~NFWelfareMgr()
{
}

int NFWelfareMgr::CreateInit()
{
    m_dwLastIDChangeUnixSec = 0;
    m_dwConfLoadUnixSec = 0;
    m_dwUseLastConfLoadUnixSec = 0;
    return 0;
}

int NFWelfareMgr::ResumeInit()
{
    return 0;
}

int NFWelfareMgr::ProcessMsgWorldWelfareSyncOpenShowRes(const proto_ff::SSWorldWelfareSyncOpenShowRes* pMsg)
{
    int iRetCode = 0;
    CHECK_NULL(0, pMsg);

    iRetCode = LoadShowAndOpenIDs(pMsg);
    CHECK_ERR(0, iRetCode, "LoadShowAndOpenIDs failed");
    return 0;
}

int NFWelfareMgr::ProcessMsgWorldWelfareSyncConfRes(const proto_ff::SSWorldWelfareSyncConfRes* pMsg)
{
    CHECK_NULL(0, pMsg);

    if (m_dwConfLoadUnixSec != 0 && m_dwConfLoadUnixSec == pMsg->m_dwconfloadunixsec())
    {
        LOG_INFO(0, "has the version conf, do nothing, m_dwConfLoadUnixSec:{}", NFTimeUtility::DateTimeToStr(m_dwConfLoadUnixSec))
        return 0;
    }

    static NFWelfareConf stCWelfareConfTemp;
    stCWelfareConfTemp.Reset();

    for (int i = 0; i < pMsg->m_astconf_size(); ++i)
    {
        const proto_ff::PBWelfareConfOne& stConfOne = pMsg->m_astconf(i);
        NFWelfareConfOne* pConf = stCWelfareConfTemp.AllocConf(stConfOne.m_stwelfaredesc().m_welfareid());
        CHECK_NULL_WF(0, pConf, "welfareId:{}", stConfOne.m_stwelfaredesc().m_welfareid());
        if (!pConf->GetConf().FromPb(stConfOne))
        {
            CHECK_ERR(0, -1, "FromPb failed, welfareId:{} desc:", stConfOne.m_stwelfaredesc().m_welfareid(), stConfOne.m_stwelfaredesc().DebugString());
        }
    }

    if (stCWelfareConfTemp.GetConf().size() <= 0)
    {
        CHECK_ERR(0, -1, "welfare conf is empty");
    }

    m_Conf = stCWelfareConfTemp;
    m_dwConfLoadUnixSec = pMsg->m_dwconfloadunixsec();
    if (m_dwConfLoadUnixSec >= m_dwUseLastConfLoadUnixSec)
    {
        LOG_INFO(0, "get conf success, m_dwConfLoadUnixSec:{}", NFTimeUtility::DateTimeToStr(m_dwConfLoadUnixSec))
        NFServiceWelfare::OnConfChange();
    }
    return 0;
}

int NFWelfareMgr::LoadShowAndOpenIDs(const proto_ff::SSWorldWelfareSyncOpenShowRes* pMsg)
{
    CHECK_NULL(0, pMsg);

    WelfareOpenShowWorldData oldOpenShowData = m_stWorldOpenShowData;
    m_stWorldOpenShowData.Init();
    m_stWorldOpenShowData.FromPb(pMsg->m_stopenshowdata());
    bool bIDChange = false;
    if (m_stWorldOpenShowData.m_aullShowWelfareID.size() != oldOpenShowData.m_aullShowWelfareID.size())
    {
        bIDChange = true;
    }
    else
    {
        for (auto iter = m_stWorldOpenShowData.m_aullShowWelfareID.begin(); iter != m_stWorldOpenShowData.m_aullShowWelfareID.end(); ++iter)
        {
            if (oldOpenShowData.m_aullShowWelfareID.find(*iter) == oldOpenShowData.m_aullShowWelfareID.end())
            {
                bIDChange = true;
                break;
            }
        }

        for (auto iter = oldOpenShowData.m_aullShowWelfareID.begin(); iter != oldOpenShowData.m_aullShowWelfareID.end(); ++iter)
        {
            if (m_stWorldOpenShowData.m_aullShowWelfareID.find(*iter) == m_stWorldOpenShowData.m_aullShowWelfareID.end())
            {
                bIDChange = true;
                break;
            }
        }
    }

    if (!bIDChange)
    {
        if (m_stWorldOpenShowData.m_aullOpenWelfareID.size() != oldOpenShowData.m_aullOpenWelfareID.size())
        {
            bIDChange = true;
        }
        else
        {
            for (auto iter = m_stWorldOpenShowData.m_aullOpenWelfareID.begin(); iter != m_stWorldOpenShowData.m_aullOpenWelfareID.end(); ++iter)
            {
                if (oldOpenShowData.m_aullOpenWelfareID.find(*iter) == oldOpenShowData.m_aullOpenWelfareID.end())
                {
                    bIDChange = true;
                    break;
                }
            }

            for (auto iter = oldOpenShowData.m_aullOpenWelfareID.begin(); iter != oldOpenShowData.m_aullOpenWelfareID.end(); ++iter)
            {
                if (m_stWorldOpenShowData.m_aullOpenWelfareID.find(*iter) == m_stWorldOpenShowData.m_aullOpenWelfareID.end())
                {
                    bIDChange = true;
                    break;
                }
            }
        }
    }

    if (!bIDChange)
    {
        return 0;
    }

    uint32_t oldLastIDChangeUnixSec = m_dwLastIDChangeUnixSec;
    m_dwLastIDChangeUnixSec = NF_ADJUST_TIMENOW();

    LOG_INFO(0, "id change, oldLastIDChangeUnixSec:{} newLastIDChangeUnixSec:{} oldOpenShowData:{} newOpenShowData:{}", std::string(NFTimeUtility::DateTimeToStr(oldLastIDChangeUnixSec)),
        std::string(NFTimeUtility::DateTimeToStr(m_dwLastIDChangeUnixSec)), oldOpenShowData.ShortDebugString(), m_stWorldOpenShowData.ShortDebugString());
    return 0;
}

int NFWelfareMgr::ProcessMsgWorldWelfareSyncDBDataRes(const proto_ff::SSWorldWelfareSyncDBDataRes* pMsg)
{
    CHECK_NULL(0, pMsg);
    m_stWorldDBData.FromPb(pMsg->m_stwelfaredbworlddata());
    return 0;
}

int NFWelfareMgr::SyncData(const proto_ff::SSWorldWelfareSyncAllData& dbData)
{
    int iRet = dbData.result();
    CHECK_ERR(0, iRet, "SyncData failed, result:{}", dbData.result());
    iRet = ProcessMsgWorldWelfareSyncConfRes(&dbData.m_stconfres());
    CHECK_ERR(0, iRet, "ProcessMsgWorldWelfareSyncConfRes failed");

    iRet = ProcessMsgWorldWelfareSyncOpenShowRes(&dbData.m_stopenshowres());
    CHECK_ERR(0, iRet, "ProcessMsgWorldWelfareSyncConfRes failed");

    iRet = ProcessMsgWorldWelfareSyncDBDataRes(&dbData.m_stdbdatares());
    CHECK_ERR(0, iRet, "ProcessMsgWorldWelfareSyncConfRes failed");

    return 0;
}

int NFWelfareMgr::Awake()
{
    RegisterServerMessageWithModule(NF_ST_LOGIC_SERVER, SS_MSGID_WORLD, SS_SUB_MSGID_WORLD_WELFARE_SYNC_CONF);
    RegisterServerMessageWithModule(NF_ST_LOGIC_SERVER, SS_MSGID_WORLD, SS_SUB_MSGID_WORLD_WELFARE_SYNC_OPENSHOW);
    RegisterServerMessageWithModule(NF_ST_LOGIC_SERVER, SS_MSGID_WORLD, SS_SUB_MSGID_WORLD_WELFARE_SYNC_DBDATA);
    return 0;
}

int NFWelfareMgr::OnHandleServerMessage(uint64_t unLinkId, NFDataPackage& packet)
{
    if (!NFGlobalSystem::Instance()->GetGlobalPluginManager()->IsInited(NF_ST_LOGIC_SERVER))
    {
        NFLogError(NF_LOG_DEFAULT, packet.nParam1, "Logic Server not inited, drop client msg:{}", packet.ToString());
        return -1;
    }

    if (NFGlobalSystem::Instance()->GetGlobalPluginManager()->IsServerStopping())
    {
        NFLogError(NF_LOG_DEFAULT, packet.nParam1, "Logic Server is Stopping, drop client msg:{}", packet.ToString());
        return -1;
    }

    if (packet.mModuleId == SS_MSGID_WORLD)
    {
        switch (packet.nMsgId)
        {
            case SS_SUB_MSGID_WORLD_WELFARE_SYNC_CONF:
            {
                OnHandleWorldWelfareSyncConf(unLinkId, packet);
                break;
            }
            case SS_SUB_MSGID_WORLD_WELFARE_SYNC_OPENSHOW:
            {
                OnHandleWorldWelfareSync(unLinkId, packet);
                break;
            }
            case SS_SUB_MSGID_WORLD_WELFARE_SYNC_DBDATA:
            {
                OnHandleWorldWelfareSyncDBData(unLinkId, packet);
                break;
            }
            default:
            {
                NFLogError(NF_LOG_DEFAULT, packet.nParam1, "Logic Server Get UnHandle Msg:{}", packet.ToString());
                break;
            }
        }
    }

    return 0;
}

int NFWelfareMgr::OnHandleWorldWelfareSyncConf(uint64_t unLinkId, NFDataPackage& packet)
{
    proto_ff::SSWorldWelfareSyncConfRes res;
    CLIENT_MSG_PROCESS_WITH_PRINTF(packet, res);
    ProcessMsgWorldWelfareSyncConfRes(&res);
    return 0;
}

int NFWelfareMgr::OnHandleWorldWelfareSync(uint64_t unLinkId, NFDataPackage& packet)
{
    proto_ff::SSWorldWelfareSyncOpenShowRes res;
    CLIENT_MSG_PROCESS_WITH_PRINTF(packet, res);
    ProcessMsgWorldWelfareSyncOpenShowRes(&res);
    return 0;
}

int NFWelfareMgr::OnHandleWorldWelfareSyncDBData(uint64_t unLinkId, NFDataPackage& packet)
{
    proto_ff::SSWorldWelfareSyncDBDataRes res;
    CLIENT_MSG_PROCESS_WITH_PRINTF(packet, res);
    ProcessMsgWorldWelfareSyncDBDataRes(&res);
    return 0;
}

int NFWelfareMgr::AfterObjFromDBLoaded(NF_SERVER_TYPE serverType)
{
    if (serverType != NF_ST_LOGIC_SERVER) return 0;

    if (EN_OBJ_MODE_INIT == NFShmMgr::Instance()->GetRunMode())
    {
        SyncReq(NF_ST_LOGIC_SERVER, NF_ST_WORLD_SERVER, 0, SS_MSGID_WORLD, proto_ff::SS_SUB_MSGID_WORLD_SYNC_WELFARE_DATA);
    }
    return 0;
}

int NFWelfareMgr::AfterAppInitFinish()
{
    SyncReq(NF_ST_LOGIC_SERVER, NF_ST_WORLD_SERVER, 0, SS_MSGID_WORLD, proto_ff::SS_SUB_MSGID_WORLD_SYNC_WELFARE_DATA);
    return 0;
}
